//
//  CommentViewController.m
//  觅影
//
//  Created by lanou on 16/4/8.
//  Copyright © 2016年  陶虹. All rights reserved.
//

#import "CommentViewController.h"
#import "CommentTableViewCell.h"
#import "CommentHeaderView.h"
#import "CommentModel.h"
#import "HeaderModel.h"

@interface CommentViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *modelArray;
@property(nonatomic, strong)HeaderModel *headerModel;
@property(nonatomic, strong)UITextField *textField;
@end

@implementation CommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"热门话题";
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"CommentTableViewCell" bundle:nil] forCellReuseIdentifier:@"CommentCell"];
    [self.tableView registerClass:[CommentHeaderView class] forHeaderFooterViewReuseIdentifier:@"header"];
    NSString *urlString = [NSString stringWithFormat:@"http://static.v6v7.com/snowman_api/movie_traces/topic_simple?topic_id=%d",[self.myId intValue]];
    
    // 表头数据请求
    [RequestManager requestWithUrl:urlString requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *resultDic = dic[@"result"];
        self.headerModel = [[HeaderModel alloc]init];
        [self.headerModel setValuesForKeysWithDictionary:resultDic];
        NSDictionary *userDic = resultDic[@"user"];
        [self.headerModel setValuesForKeysWithDictionary:userDic];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    } error:^(NSError *error) {
        NSLog(@"请求错误");
    }];
    
    NSString *string = [NSString stringWithFormat:@"http://static.v6v7.com/snowman_api/movie_traces/topic_reply_list?page=1&page_size=15&topic_id=%d",[self.myId intValue]];
    // cell数据请求
    [RequestManager requestWithUrl:string requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *resultDic = dic[@"result"];
        NSArray *dataArray = resultDic[@"data"];
        self.modelArray = [NSMutableArray array];
        for (NSDictionary *dataDic in dataArray) {
            CommentModel *model = [[CommentModel alloc]init];
            [model setValuesForKeysWithDictionary:dataDic];
            [self.modelArray addObject:model];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }
        
    } error:^(NSError *error) {
        NSLog(@"请求错误");
    }];
    
    // 添加评论textField
    self.textField = [[UITextField alloc]initWithFrame:CGRectMake(30, KHEIGHT - 30, KWIDTH - 60, 30)];
    self.textField.borderStyle = UITextBorderStyleRoundedRect;
    self.textField.placeholder = @"你的评论";
    self.textField.delegate = self;
    [self.view addSubview:self.textField];
    
    // 添加键盘弹出的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil];
    // 添加键盘回收的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardHide:) name:UIKeyboardWillHideNotification object:nil];
    
    // 给tableView添加一个轻拍手势 点击回收键盘
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideAction:)];
    [self.tableView addGestureRecognizer:tap];
    
}

#pragma mark --- 键盘弹出的通知 ---
- (void)keyBoardShow:(NSNotification *)notification
{
    NSDictionary *info = notification.userInfo;
    // 拿到弹出键盘的一个整体的信息
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize size = [value CGRectValue].size;
    self.textField.frame = CGRectMake(30, KHEIGHT - 30 - size.height, KWIDTH - 60, 30);
}

#pragma mark --- 键盘回收的通知 ---
- (void)keyBoardHide:(NSNotification *)notification
{
    self.textField.frame = CGRectMake(30, KHEIGHT-30, KWIDTH - 60, 30);
    }

#pragma mark --- 点击tableView回收键盘 ---
- (void)hideAction:(UITapGestureRecognizer *)tap
{
    [self.textField resignFirstResponder];
}


#pragma mark --- 点击return请求数据发表评论 ---
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    /* Configure session, choose between:
     * defaultSessionConfiguration
     * ephemeralSessionConfiguration
     * backgroundSessionConfigurationWithIdentifier:
     And set session-wide properties, such as: HTTPAdditionalHeaders,
     HTTPCookieAcceptPolicy, requestCachePolicy or timeoutIntervalForRequest.
     */
    NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    /* Create session, and optionally set a NSURLSessionDelegate. */
    NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil];
    
    /* Create the Request:
     My API (POST http://static.v6v7.com/snowman_api/movie_traces/add_topic_reply)
     */
    
    NSURL* URL = [NSURL URLWithString:@"http://static.v6v7.com/snowman_api/movie_traces/add_topic_reply"];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
    request.HTTPMethod = @"POST";
    
    //sessionid=p6r84oeanc2309sk4j1is2baxdq2q55b
    
    // Headers
    [request addValue:@"sessionid=mvbly4g7678j33vz0114g66txroocgol" forHTTPHeaderField:@"Cookie"];
    [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    NSString *UTF8String = [self.textField.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    // Form URL-Encoded Body
    NSDictionary* bodyParameters = @{
                                     @"content": UTF8String,
                                     @"topic_id": self.myId,
                                     };
    //request.HTTPBody = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding];
    
    [request setHTTPBody:[self dicToDataWithDic:bodyParameters]];
    /* Start a new Task */
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil) {
            NSDictionary *backDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"==============%@",backDic);
            NSString *msg = backDic[@"msg"];
            NSString *msgString = [msg stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
            NSDictionary *resultDic = backDic[@"result"];
            NSString *username = resultDic[@"username"];
            NSString *contentString = resultDic[@"content"];
            NSString *content = [contentString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
            NSString *dateString = resultDic[@"date"];
            NSString *date = [dateString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
            NSString *header = resultDic[@"header"];
            /////////////////////////////
            NSLog(@"%@",header);
            if ([msgString isEqualToString:@"创建成功"]) {
                // Success
                //刷新数据
                CommentModel *model = [[CommentModel alloc]init];
                model.header = header;
                model.date = date;
                model.content = content;
                model.username = username;
                [self.modelArray insertObject:model atIndex:0];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView reloadData];
              });
                

//                NSString *string = [NSString stringWithFormat:@"http://static.v6v7.com/snowman_api/movie_traces/topic_reply_list?page=1&page_size=15&topic_id=%d",[self.myId intValue]];
//                [RequestManager requestWithUrl:string requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
//                    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//                    NSDictionary *resultDic = dic[@"result"];
//                    NSArray *dataArray = resultDic[@"data"];
//                    self.modelArray = [NSMutableArray array];
//                    for (NSDictionary *dataDic in dataArray) {
//                        CommentModel *model = [[CommentModel alloc]init];
//                        [model setValuesForKeysWithDictionary:dataDic];
//                        [self.modelArray addObject:model];
//                    }
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [self.tableView reloadData];
//                    });
//                    NSLog(@"评论个数：%ld", self.modelArray.count);
//                    
//                } error:^(NSError *error) {
//                    NSLog(@"请求错误");
//                }];

                
            }
            else
            {
                
               dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"提示" message:@"评论失败" preferredStyle:UIAlertControllerStyleActionSheet];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                [sheet addAction:cancelAction];
                [self presentViewController:sheet animated:YES completion:nil];
                                });
            }
        }
        else
        {
            // Failure
            NSLog(@"URL Session Task Failed: %@", [error localizedDescription]);
        }
    }];
    [task resume];
    
    
    self.textField.text = @"";
    [self.textField resignFirstResponder];
    return YES;
}


// 将字典里的键值对 按照key = value 拼接成字符串 最后用&符号连接所有拼好的字符串
- (NSData *)dicToDataWithDic:(NSDictionary *)dic
{
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *key in dic) {
        NSString *string = [NSString stringWithFormat:@"%@=%@", key, dic[key]];
        [array addObject:string];
    }
    // 把数组里的东西每个用&来拼接
    NSString *dataString = [array componentsJoinedByString:@"&"];
    return [dataString dataUsingEncoding:NSUTF8StringEncoding];
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommentCell"];
    CommentModel *model = self.modelArray[indexPath.row];
    cell.model  = model;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    CommentHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    view.model = self.headerModel;
    return view;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
     CommentModel *model = self.modelArray[indexPath.row];
    return [CommentTableViewCell cellForHeight:model];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 110;
}





@end
